package com.ruoyi.web.controller.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.user.UserInvalidException;
import com.ruoyi.common.json.JSON;
import com.ruoyi.domain.UserProfile;
import com.ruoyi.service.IUserProfileService;
import com.ruoyi.service.IUserService;
import com.ruoyi.util.BeanCopierUtils;
import com.ruoyi.util.CosClientUtil;
import com.ruoyi.util.FileUtil;
import com.ruoyi.web.controller.wechat.request.AvatarRequest;
import com.ruoyi.web.controller.wechat.request.EncryptedUserRequest;
import com.ruoyi.web.controller.wechat.response.LoginResponse;
import com.ruoyi.web.controller.wechat.response.UserProfileResponse;
import com.ruoyi.web.core.config.EncryptUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 登录
 *
 * @author chenchuan2
 * @date 2023-01-12 20:20:05
 */
@RestController
@RequestMapping("/wechat-api/ygUser")
@Slf4j
public class UserController extends AuthController {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserProfileService userProfileService;

    @Autowired
    private CosClientUtil cosClientUtil;


    @ApiOperation("用户登录")
    @GetMapping("/login")
    public R<LoginResponse> login(@ApiParam(value = "微信登录code") String code, @ApiParam(value = "inviteId") String inviteId) throws WxErrorException {

        if (StringUtils.isBlank(code)) {
            throw new UserInvalidException();
        }

        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);

        LoginResponse response = new LoginResponse();
        response.setYgid(EncryptUtil.encrypt(session.getOpenid()));
        response.setSessionKey(session.getSessionKey());
        userService.login(session, inviteId);

        return R.ok(response);
    }


    /**
     * 解密用户信息
     *
     * @return
     * @throws WxErrorException
     */
    @ApiOperation("解密用户信息")
    @PostMapping("/info")
    public R<?> info(@RequestBody @Validated EncryptedUserRequest encryptedUserRequest) throws Exception {
        String openId = getOpenId();

        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(encryptedUserRequest.getJsCode());
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionInfo.getSessionKey(),
                encryptedUserRequest.getEncryptedData(), encryptedUserRequest.getIv());
        log.info("userInfo[{}]", JSON.marshal(userInfo));

        userService.upsertUserInfo(openId, userInfo);

        return R.ok(userInfo);

    }

    @PostMapping("/phoneNum")
    public R<?> phoneNum(@RequestBody @Validated EncryptedUserRequest encryptedUserRequest) throws Exception {
        String openId = getOpenId();

        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(encryptedUserRequest.getJsCode());

        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(),
                encryptedUserRequest.getEncryptedData(), encryptedUserRequest.getIv());
        log.info("phoneNum[{}]", JSON.marshal(phoneNoInfo));

        userService.upsertPhoneNo(openId, phoneNoInfo);

        return R.ok(phoneNoInfo);

    }

    @GetMapping("/profile")
    public R<UserProfileResponse> queryUserInfo() {
        String openId = getOpenId();
        UserProfile userProfile = userProfileService.selectUserProfileByOpenId(openId);
        UserProfileResponse userProfileResponse = BeanCopierUtils.copyBean(userProfile, UserProfileResponse::new);
        return R.ok(userProfileResponse);
    }

    @PostMapping("/updateAvatar")
    public R<String> updateAvatar(@RequestBody AvatarRequest request) throws IOException {
        String openId = getOpenId();

        //base64 上传到腾讯云
        String userImg = cosClientUtil.uploadImgToCos(request.getAvatarBase64(), request.getFileName());
        UserProfile userProfile = userProfileService.selectUserProfileByOpenId(openId);
        if (null == userProfile) {
            userProfile = new UserProfile();
            userProfile.setAvatarUrl(userImg);
            userProfile.setOpenId(openId);
            userProfileService.insertUserProfile(userProfile);
        } else {
            userProfile.setAvatarUrl(userImg);
            userProfileService.updateUserProfile(userProfile);
        }
        return R.ok(userImg);
    }

}
